#include "stdafx.h"
#include "GameInputListener.h"


GameInputListener::GameInputListener(Ogre::RenderWindow* window, Ogre::Camera* camera, Ogre::SceneManager* manager)
{
	this->mWindow = window;
	this->mCamera = camera;
	this->mSceneMgr = manager;
	this->startOIS();

	// Creation de l'instance de la gameloop
	this->gameLoop = new GameLoop(this->mMouse, this->mKeyboard, this->mCamera, this->mSceneMgr);
}


GameInputListener::~GameInputListener(void)
{
	delete this->gameLoop;
	Ogre::WindowEventUtilities::removeWindowEventListener(mWindow, this);
    windowClosed(mWindow);
}

bool GameInputListener::frameRenderingQueued(const Ogre::FrameEvent& evt)
{
    if(mWindow->isClosed())
        return false;

	if (mMouse)
		mMouse->capture();

	if (mKeyboard)
		mKeyboard->capture();


	// Appel des methodes Update() et Draw() de la gameloop
	if (!this->gameLoop->Update(evt))
		return false;

    return true;
}

void GameInputListener::windowResized(Ogre::RenderWindow* wnd)
{
    unsigned int width, height, depth;
    int left, top;
    wnd->getMetrics(width, height, depth, left, top);
 
    const OIS::MouseState &ms = mMouse->getMouseState();
    ms.width = width;
    ms.height = height;
}

void GameInputListener::windowClosed(Ogre::RenderWindow* wnd)
{
    if( wnd == mWindow )
    {
        if( mInputManager )
        {
            mInputManager->destroyInputObject( mMouse );
            mInputManager->destroyInputObject( mKeyboard );
 
            OIS::InputManager::destroyInputSystem(mInputManager);
            mInputManager = 0;
        }
    }
}

void GameInputListener::startOIS()
{
	// Ajout d'une ligne dans le log de Ogre
	Ogre::LogManager::getSingletonPtr()->logMessage("*** Initializing OIS ***");

	OIS::ParamList pl;
	size_t windowHnd = 0;
	std::ostringstream windowHndStr;
 
	mWindow->getCustomAttribute("WINDOW", &windowHnd);
	windowHndStr << windowHnd;
	pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));

	mInputManager = OIS::InputManager::createInputSystem( pl );
	mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject( OIS::OISMouse, false ));
	mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject( OIS::OISKeyboard, false ));

	windowResized(mWindow);
	Ogre::WindowEventUtilities::addWindowEventListener(mWindow, this);
}